package com.xjh.t.controller;

import com.xjh.t.common.ActiverUser;
import com.xjh.t.common.ResultObj;
import com.xjh.t.common.WebUtils;
import com.xjh.t.domain.Loginfo;
import com.xjh.t.service.ILoginfoService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
@RequestMapping("login")
public class LoginController {

    @Autowired
    private ILoginfoService loginfoService;
    @RequestMapping("login")
    public ResultObj login(String loginname, String pwd)
    {
        Subject subject = SecurityUtils.getSubject();
        AuthenticationToken token = new UsernamePasswordToken(loginname,pwd);
        try {
            subject.login(token);
            ActiverUser activerUser = (ActiverUser)subject.getPrincipal();
            WebUtils.getSession().setAttribute("user",activerUser.getUser());

            //登陆日志
           /* Loginfo entity = new Loginfo();
            entity.setLoginname(activerUser.getUser().getName()+"_"+activerUser.getUser().getLoginname());
            entity.setLoginip(WebUtils.getRequest().getRemoteAddr());
            entity.setLogintime(new Date());
            loginfoService.save(entity);*/
            return  ResultObj.LOGIN_SUCESS;
        }
        catch (AuthenticationException e)
        {
            e.printStackTrace();
            return ResultObj.LOGIN_FAIL;
        }
    }
}

